<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="theme-color" content="#4374A5">
  <title>PWA Manifest Demo</title>
  <link rel="manifest" href="./manifest.json">
  <link rel="stylesheet" href="./style.css">
</head>
<body>
  <div>Hello PWA Manifest Demo</div>
  <button hidden id="installBtn">安装应用</button>
  <!-- index db -->
  <br />
  <div>IndexDB Demo</div>
  <div>
    <input id="value" type="text" placeholder="请输入待办事项"/>
    <button id="submit">添加</button>
  </div>
  <div id="list"></div>
  <div>
    <button onclick="xc_filter('all')">显示所有</button>
    <button onclick="xc_filter('completed')">显示已完成</button>
    <button onclick="xc_filter('doing')">显示未完成</button>
    <button onclick="xc_removeAll()">清空</button>
  </div>
  
  <!-- cache -->
  <br/>
  <div class="panel">
    <h1>斜体</h1>
    <img src="./images/launcher-icon.png"/>
  </div>

  <!-- sync -->
  <div>当前网络状态：<span id="network-status">在线</span></div>
  <div>
    <input id="sync_demo_name" type="text" placeholder="请输入待办事项"/>
    <button id="sync_demo_submit">添加</button>
  </div>
  <div id="sync_demo_list"></div>

  <!-- push notification -->
  <button id="send-push">点击发送消息</button>

  <script src="./main.js"></script>
  <!-- sync-demo -->
  <script src="./db.js"></script>
  <script src="./ui.js"></script>
  <script src="./network.js"></script>
  <script>
    // https://caniuse.com/?search=serviceworker
    window.addEventListener('load', function() {

      if ('serviceWorker' in navigator) {
        // param2 { scope: './' }
        // navigator.serviceWorker.register('./sw.js').then(function(registration) {
          // do something...

          // 状态
          // {
          //   const newWorker = registration.installing;
          //    newWorker.addEventListener('statechange', function() {
          //     console.log(newWorker.state);
          //   })

          //   const waitWorker = registration.waiting;
          //   waitWorker.addEventListener('statechange', function() {
          //     console.log(waitWorker.state);
          //   })

          //   const activeWorker = registration.active;
          //   activeWorker.addEventListener('statechange', function() {
          //     console.log(activeWorker.state);
          //   })
          // }

          // registration.addEventListener('updatefound', function() {

          // });

        // }).catch(function(err) {
          // do something...

        // });
      }

      let appPromptEvent = null;
      const installBtn = document.getElementById('installBtn');
      window.addEventListener('beforeinstallprompt', function(event) {
        console.log('触发事件：beforeinstallprompt');
        event.preventDefault();
        appPromptEvent = event;
        installBtn.hidden = false;
        return false;
      });

      installBtn.addEventListener('click', function() {
        if (appPromptEvent !== null) {
          appPromptEvent.prompt();
          appPromptEvent.userChoice.then(function(result) {
            if (result.outcome === 'accepted') {
              console.log('同意安装应用');
            } else {
              console.log('不同意安装应用');
            }
            appPromptEvent = null;
          });
        }
      });

      window.addEventListener('appinstalled', function() {
        console.log('应用已安装');
        installBtn.hidden = true;
      });

      // ================================= indexdb
      document.getElementById('submit').addEventListener('click', function() {
        const value = document.getElementById('value').value.trim();
        if (value.length === 0) {
          alert('待办事项不能为空');
        } else {
          xc_add(value)
        }
        xc_filter('all');
      })
      // ================================ indexdb

      // ================================ sync
      
      // network.getTodos().then(function(todos) {
      //   ui.render(todos);
      // });
      // if ('serviceWorker' in navigator && 'SyncManager' in window) {
      //   navigator.serviceWorker.register('./sw.js').then(function(registration) {
      //     document.getElementById('sync_demo_submit').addEventListener('click', function() {
      //       ui.submit(function(name) {
      //         db.addTodo(name).then(function() {
      //           registration.sync.register('add-todo').then(function() {
      //             console.log('已触发后台同步: add-todo');
      //           });
      //         });
      //       });
      //     });
      //   });
      //   navigator.serviceWorker.addEventListener('message', function(event) {
      //     ui.render(event.data);
      //   });
      // } else {
      //   document.getElementById('sync_demo_submit').addEventListener('click', function() {
      //     ui.submit(function(name) {
      //       network.addTodos([{ name: name }]).then(function(todos) {
      //         ui.render(todos);
      //       });
      //     });
      //   });
      // }

      // ================================ sync

      // ================================ push manager

      if ('serviceWorker' in navigator && 'PushManager' in window) {
        navigator.serviceWorker.register('./sw.js').then(function(registration) {
          registration.pushManager.getSubscription().then(function(subscription) {
            if (subscription) {
              console.log('通知已注册....');
              return;
            }
            registration.pushManager.subscribe({
              userVisibleOnly: true,
              applicationServerKey: getApplicationServerKey()
            }).then(function(subscription) {
              fetch('/subscribe', {
                headers: {
                  'content-type': 'application/json'
                },
                method: 'POST',
                body: JSON.stringify(subscription)
              }).then(function(response) {
                return response.json();
              }).then(function() {
                console.log('通知注册成功...');
              }).catch(function() {
                subscription.unsubscribe();
                console.log('通知注册失败...');
              })
            })
          })
        });
      }
      document.getElementById('send-push').addEventListener('click', function() {
        fetch('/push', { method: 'POST' });
      });

      // ================================ push manager
    });

    // 注销
    // {
    //   const serviceWorker = navigator.serviceWorker;
    //   if (typeof serviceWorker.getRegistrations === 'function') {
    //     serviceWorker.getRegistrations().then(function(registrations) {
    //       registrations.forEach(function(registration) {
    //         registration.unregister();
    //       });
    //     });
    //   } else if (typeof serviceWorker.getRegistration === 'function') {
    //     serviceWorker.getRegistration().then(function(registration) {
    //       registration.unregister();
    //     })
    //   }
    // }


    navigator.serviceWorker.addEventListener('controllerchange', function() {

    });

    window.addEventListener('offline', function() {
      document.getElementById('network-status').innerHTML = '离线';
    });

    window.addEventListener('online', function() {
      document.getElementById('network-status').innerHTML = '在线';
    });

    function urlB64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4);
      const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/');
      const rawData = window.atob(base64);
      const outputArray = new Uint8Array(rawData.length);
      for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
      }
      return outputArray;
    }

    function getApplicationServerKey() {
      return urlB64ToUint8Array(
        'BJwIJEHlX00w3wsVhDkKH3e_aC6wvAl3XKyILZzfM8zvRG-kZK8AtVBRaINPuIFAgjWlAs7jeZkaLgDpdhrQbWw'
      );
    }



  </script>
</body>
</html>